<template>
  <div>
    <el-form
      ref="form"
      v-if="renderFormBuilder"
      :model="form"
      :label-width="
        labelWidth.endsWith('px') || labelWidth.endsWith('%')
          ? labelWidth
          : labelWidth + 'px'
      "
    >
      <div v-for="(item, index) in formBuilder" :key="index">
        <el-form-item v-if="item.type === 'text'" :label="item.title">
          <el-input
            v-model="form[item.field]"
            :placeholder="item.placeholder ? item.placeholder : item.title"
          />
        </el-form-item>

        <el-form-item v-if="item.type === 'number'" :label="item.title">
          <el-input
            v-model="form[item.field]"
            type="number"
            :placeholder="item.placeholder ? item.placeholder : item.title"
          />
        </el-form-item>

        <el-form-item v-if="item.type === 'select'" :label="item.title">
          <el-select
            v-model="form[item.field]"
            :placeholder="item.placeholder ? item.placeholder : item.title"
          >
            <el-option
              v-for="(unit, _index) in item.options"
              :label="unit.content"
              :value="unit.value"
              :key="_index"
            />
          </el-select>
        </el-form-item>

        <el-form-item v-if="item.type === 'switch'" :label="item.title">
          <el-switch v-model="form[item.field]" />
        </el-form-item>

        <el-form-item v-if="item.type === 'checkbox'" :label="item.title">
          <el-checkbox-group v-model="form[item.field]">
            <el-checkbox
              v-for="(unit, _index) in item.options"
              :checked="form[item.field].indexOf(unit.value) !== -1"
              :label="unit.content"
              :value="unit.value"
              :key="_index"
            />
          </el-checkbox-group>
        </el-form-item>

        <el-form-item v-if="item.type === 'radio'" :label="item.title">
          <el-radio-group v-model="form[item.field]">
            <el-radio
              v-for="(unit, _index) in item.options"
              :label="unit.value"
              :key="_index"
              >{{ unit.content }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="item.type === 'textarea'" :label="item.title">
          <el-input v-model="form[item.field]" type="textarea" />
        </el-form-item>

        <el-form-item v-if="item.type === 'upload'" :label="item.title">
          <el-upload
            drag
            :action="item.url"
            :data="{
              field: item.field,
              multiple: item.multiple ? item.multiple : false,
            }"
            :on-success="handleUpladSuccess"
            :multiple="item.multiple ? item.multiple : false"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <div class="el-upload__tip" v-if="item.tip" slot="tip">
              {{ item.tip }}
            </div>
          </el-upload>
        </el-form-item>

        <el-form-item v-if="item.type === 'date'" :label="item.title">
          <el-date-picker
            v-model="form[item.field]"
            type="date"
            :placeholder="item.placeholder"
            :picker-options="pickerOptions"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item v-if="item.type === 'daterange'" :label="item.title">
          <el-date-picker
            v-model="form[item.field]"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item v-if="item.type === 'time'" :label="item.title">
          <el-time-picker
            v-model="form[item.field]"
            :placeholder="item.placeholder"
          >
          </el-time-picker>
        </el-form-item>

        <el-form-item v-if="item.type === 'transfer'" :label="item.title">
          <el-transfer
            filterable
            :filter-placeholder="item.placeholder"
            v-model="form[item.field]"
            :titles="item.titles"
            :data="item.data"
          >
          </el-transfer>
        </el-form-item>

        <el-form-item v-if="item.type === 'more'" :label="item.title">
          <el-row
            style="margin-bottom: 10px"
            v-for="(unit, _index) in form[item.field]"
            :key="_index"
            class="flex-between"
          >
            <el-col :span="4">
              <el-input
                v-model="form[item.field][_index]['key']"
                placeholder="Key"
                style="width: 100%"
              ></el-input>
            </el-col>
            <el-col :span="1"></el-col>
            <el-col :span="4">
              <el-input
                v-model="form[item.field][_index]['content']"
                placeholder="标题"
                style="width: 100%"
              ></el-input>
            </el-col>
            <el-col :span="1"></el-col>
            <el-col :span="4">
              <el-select
                v-model="form[item.field][_index]['type']"
                placeholder="类型"
              >
                <el-option
                  v-for="(option, __index) in optionTypes"
                  :key="__index"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
            </el-col>
            <el-col :span="1"></el-col>
            <el-col :span="10">
              <el-input
                v-model="form[item.field][_index]['params']"
                style="width: 100%"
                placeholder="参数"
              >
              </el-input>
            </el-col>
            <el-col :span="1"></el-col>
            <el-col :span="5">
              <el-input
                v-model="form[item.field][_index]['value']"
                style="width: 100%"
                placeholder="默认"
              >
              </el-input>
            </el-col>
            <el-col :span="1"></el-col>
            <el-col :span="1">
              <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                @click="DelMore(item.field, _index)"
              ></el-button>
            </el-col>
          </el-row>
          <el-row>
            <el-button size="small" round @click="AddMore(item.field)"
              >添加参数</el-button
            >
          </el-row>
        </el-form-item>

        <el-form-item v-if="item.type === 'button'">
          <el-row>
            <el-col
              :span="24 / item.buttons.length"
              v-for="(btn, _index) in item.buttons"
              :key="_index"
            >
              <el-button :type="btn.type" @click="onSubmit(_index)">{{
                btn.title
              }}</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "form_builder",
  components: {},
  props: {
    submitButton: {
      type: Boolean,
      default: true,
    },
    labelWidth: {
      type: String,
      default: "75",
    },
    formBuilder: {
      default: [],
    },
    buttons: {
      type: Array,
      default: () => [
        {
          type: "primary",
          title: "提交",
          validate: true,
        },
        {
          type: "",
          title: "取消",
        },
      ],
    },
  },
  data() {
    return {
      imageUrl: "",
      form: {},
      renderFormBuilder: false,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", date);
            },
          },
          {
            text: "一周前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            },
          },
        ],
      },
      optionTypes: [
        { value: 1, label: "文本" },
        { value: 2, label: "单选框" },
        { value: 3, label: "复选框" },
        { value: 4, label: "开关" },
        { value: 5, label: "数字" },
        { value: 6, label: "选择" },
        { value: 7, label: "单图" },
        { value: 8, label: "多图" },
      ],
      fileList: [
        {
          name: "food.jpeg",
          url: "",
        },
      ],
    };
  },
  created() {
    let self = this;
    self.resetDate();
  },
  methods: {
    handleUpladSuccess(response, file, fileList) {
      if (!response.multiple || response.multiple == "false")
        fileList = fileList[0];
      this.form[response.field] = fileList;
      console.log(this.form);
    },
    AddMore(field) {
      // console.log(this.form[field])
      this.form[field].push({
        key: "",
        type: "",
        params: "",
        content: "",
        value: "",
      });
    },
    DelMore(field, index) {
      this.form[field].splice(index, 1);
    },
    resetDate() {
      let self = this;
      self.formBuilder.map((item) => {
        if (
          item.hasOwnProperty.call("options") &&
          typeof item.options === "function"
        ) {
          item.options().then((res) => {
            item.options = res.data.list.map((item) => {
              return { content: item.title, value: item.id };
            });
          });
        }
        self.$set(this.form, item["field"], item["value"]);

        if (item.type === "more") {
          if (!item.value) self.$set(this.form, item["field"], []);
        }

        if (item.type === "time") {
          let myDate = new Date();
          let h = myDate.getHours();
          let m = myDate.getMinutes();
          let s = myDate.getSeconds();
          if (item.value) {
            let arr = item["value"].split(":");
            h = arr[0];
            m = arr[1];
            if (arr.length >= 3) {
              s = arr[2];
            }else{
              s = 0
            }
          }
          self.$set(
            this.form,
            item["field"],
            new Date(
              myDate.getFullYear(),
              myDate.getMonth(),
              myDate.getDate(),
              h,
              m,
              s
            )
          );
        }
      });

      if (this.submitButton) {
        let obj = {
          type: "button",
          buttons: this.buttons,
          only: true,
        };
        let hasOnly = false;
        self.formBuilder.map((item) => {
          if (item.only) hasOnly = true;
        });
        if (!hasOnly) self.formBuilder.push(obj);
      }
      this.render("renderFormBuilder");
    },
    getData() {
      return this.form;
    },
    onSubmit(index) {
      let btn = this.formBuilder[this.formBuilder.length - 1]["buttons"][index];
      this.$refs.form.validate((valid) => {
        if (!valid) {
          console.log("validate error!");
          return false;
        }
        this.$emit("callable", { index: index, btn: btn, data: this.form });
      });
    },
    render(key, callable = null) {
      let self = this;
      self.$set(this, key, false);
      this.$nextTick(() => {
        self.$set(this, key, true);
        if (callable) callable();
      });
    },
  },
};
</script>

<style>
.line {
  text-align: center;
}

.form_c {
  text-align: center;
  line-height: 35px;
}

.flex-between {
  display: flex;
  justify-content: space-between;
}

.thumb {
  width: 80px;
  height: 80px;
}

.el-form-item__content {
  text-align: left;
}
</style>

